<template>
  <md-nav-bar title="" hideLeft :bgInfo="{ url: data.cover,showLogo:true }" />
  <!-- 顶部渐变背景 -->
  <view class="square-header">
    <view class="square-tabs">
      <view :class="['tab', tabIndex === 0 ? 'active' : '']" @click="handleTabChange(0)">音乐广场</view>
      <view :class="['tab', tabIndex === 1 ? 'active' : '']" @click="handleTabChange(1)">MV广场</view>
      <view :class="['tab', tabIndex === 2 ? 'active' : '']" @click="handleTabChange(2)">音乐商城</view>
    </view>
  </view>
  <view class="square-container">
    <!-- 音乐广场 -->
    <view v-if="tabIndex === 0" class="square-content">
      <!-- 排序按钮 -->
      <view class="sort-bar">
        <md-select v-model="data.value" :localdata="data.range" @change="change" placeholder="按热点排序" />
        <view style="position: relative">
          <input class="keyword-search" v-model="data.keyword" placeholder="搜索歌名/音乐人" @change="searchKeyword" />
          <uni-icons
              type="search"
              size="20"
              color="#01604a"
              class="search-icon"
              @click="searchKeyword"
          />

        </view>
      </view>

      <!-- 音乐卡片列表 -->
      <view class="music-list">
        <md-page-list 
          v-if="tabIndex === 0"
          :key="'music-' + tabIndex + '-music-' + Date.now()"
          :api="api.Music.list" 
          :params="{ orderBy: data.value, keyword: data.keyword ? data.keyword : '' }" 
          @change="pageChange" 
          ref="pageRef">
          <view v-for="item in data?.list" :key="item?.id" class="music-card" @click="onToMusicDetail(item)">
            <image class="music-img" :src="item?.coverUrl" mode="aspectFill" />
            <view class="music-info">
              <view class="music-title">
                <text class="music-title-name">{{ item?.name }}</text>
                <span class="music-title-score" v-if="item?.aiScore">
                  {{ item?.aiScore || '0' }}
                  <text class="music-title-fen">分</text>
                </span>
              </view>
              <view class="music-author">{{ item.memberUser?.nickname }}</view>
              <view class="music-meta">
                <view class="meta-item">
                  <image
                    class="meta-item-icon"
                    src="https://cdn.xmxiaomai.com/isong_static/square/%E8%B5%9E.png"
                    mode="widthFix"></image>
                  {{ item?.likesNum }}
                </view>
                <view class="meta-item">
                  <image
                    class="meta-item-icon"
                    src="https://cdn.xmxiaomai.com/isong_static/square/%E8%AF%84%E8%AE%BA.png"
                    mode="widthFix"></image>
                  {{ item?.commentNum }}
                </view>
                <view class="meta-item">
                  <image
                    class="meta-item-icon"
                    src="https://cdn.xmxiaomai.com/isong_static/square/%E8%BD%AC.png"
                    mode="widthFix"></image>
                  {{ item?.collectNum }}
                </view>
              </view>
            </view>
            <view class="music-arrow">
              <text class="iconfont" style="font-size: 36rpx; color: #1fa37a; font-weight: 700">&#8250;</text>
            </view>
          </view>
        </md-page-list>
      </view>
    </view>
    
    <!-- MV广场 -->
    <view v-else-if="tabIndex === 1" class="square-content" >
      <view class="sort-bar">
        <view style="position: relative">
          <input class="keyword-search" v-model="data.mvKeyword" placeholder="搜索歌名" @change="mvSearchKeyword" />
          <uni-icons
              type="search"
              size="20"
              color="#01604a"
              class="search-icon"
              @click="mvSearchKeyword"
          />
        </view>
      </view>
      <view class="mv-list">
        <md-page-list 
          v-if="tabIndex === 1"
          :key="'mv-' + tabIndex + '-mv-' + Date.now()"
          :api="api.Mv.publicPage" 
          :params="{ musicName: data.mvKeyword ? data.mvKeyword : '' }" 
          @change="mvPageChange" 
          ref="mvPageRef">
          <view v-for="item in data?.mvList" :key="item?.id" class="mv-card" @click="onToMvDetail(item)">
            <image :src="item.coverUrl || 'https://cdn.xmxiaomai.com/isong_static/music/music-default-avatar.png'" mode="aspectFill"></image>
            <view class="list-item-title">{{ item.musicName }}</view>
          </view>
        </md-page-list>
      </view>
    </view>
    
    <!-- 音乐商城 -->
    <view v-else-if="tabIndex === 2" class="square-content">
      <view class="mall-subtabs">
        <view
          v-for="(item, idx) in subTabs"
          :key="idx"
          :class="['subtab', subTab === idx ? 'active' : '']"
          @click="onChangeSubTab(idx)">
          {{ item }}
        </view>
      </view>

      <!-- 商品卡片瀑布流 -->
      <md-page-list 
        v-if="tabIndex === 2"
        :key="'goods-' + tabIndex + '-goods-' + Date.now()"
        :api="api.Order.productPage" 
        :params="{ type: subTab + 1 }" 
        @change="goodSPageChange" 
        ref="goodsPageRef">
        <view class="goods-list">
          <view v-for="(item, idx) in data.goodsList" :key="idx" class="goods-card" @click="onToShopDetail(item)">
            <image class="goods-img" :src="item.picUrl" mode="aspectFill" />
            <view class="goods-info">
              <view class="goods-title">{{ item.title }}</view>
              <view class="goods-author">{{ item.author }}</view>
            </view>
            <view class="goods-price-bar">
              <view class="goods-price"><text class="goods-price-unit">￥</text>{{ formatUnitCentToYuan(item.price, 2) }}</view>
            </view>
          </view>
        </view>
      </md-page-list>
    </view>

    <bottom-tab-bar :current="1" />
  </view>
</template>

<script lang="ts" setup>
import { reactive, ref, nextTick } from 'vue';
import { onHide } from '@dcloudio/uni-app';
// 接口
import api from '@/api/index';
import type { Music, User } from '@/api/data';
import { formatUnitCentToYuan } from '@/utils/util';

const data = reactive({
  cover: 'https://cdn.xmxiaomai.com/isong_static/evaluation/indexTopBg.png',
  value: 0,
  range: [
    { value: 0, text: '发布时间' },
    { value: 1, text: '播放量' },
    { value: 2, text: '点赞数' },
    { value: 3, text: '测评分数' },
  ],
  list: [] as Music.List.Data['list'],
  keyword: null,
  mvKeyword: null,
  mvList: [] as any[],
  goodsList: [] as User.Order.ProductList[]
});
const pageRef = ref<any>(null);
const mvPageRef = ref<any>(null);
const goodsPageRef = ref<any>(null);

const tabIndex = ref(0);
const subTab = ref(0);
const subTabs = ['诗词', '成曲', 'demo'];

// 监听tab切换，清理组件引用
const handleTabChange = (newTabIndex: number) => {
  // 清理之前的组件引用
  if (tabIndex.value !== newTabIndex) {
    // 清理音乐列表引用和数据
    if (tabIndex.value === 0) {
      if (pageRef.value) {
        pageRef.value = null;
      }
      data.list = [];
    }
    // 清理MV列表引用和数据
    if (tabIndex.value === 1) {
      if (mvPageRef.value) {
        mvPageRef.value = null;
      }
      data.mvList = [];
    }
    // 清理商品列表引用和数据
    if (tabIndex.value === 2) {
      if (goodsPageRef.value) {
        goodsPageRef.value = null;
      }
      data.goodsList = [];
    }
  }
  
  tabIndex.value = newTabIndex;
  
  // 强制清理所有组件引用，确保不会有残留
  nextTick(() => {
    // 清理所有不相关的组件引用
    if (tabIndex.value !== 0) {
      pageRef.value = null;
      data.list = [];
    }
    if (tabIndex.value !== 1) {
      mvPageRef.value = null;
      data.mvList = [];
    }
    if (tabIndex.value !== 2) {
      goodsPageRef.value = null;
      data.goodsList = [];
    }
    
    // 强制触发响应式更新
    if (tabIndex.value === 0) {
      data.mvList = [];
      data.goodsList = [];
    } else if (tabIndex.value === 1) {
      data.list = [];
      data.goodsList = [];
    } else if (tabIndex.value === 2) {
      data.list = [];
      data.mvList = [];
    }
    
    // 强制清理所有组件引用，防止残留
    setTimeout(() => {
      if (tabIndex.value !== 0) {
        pageRef.value = null;
      }
      if (tabIndex.value !== 1) {
        mvPageRef.value = null;
      }
      if (tabIndex.value !== 2) {
        goodsPageRef.value = null;
      }
    }, 100);
  });
};

const onToMusicDetail = (item: Music.List.ListVo) => {
  uni.navigateTo({
    url: `/pages/sub/square/musicDetail?id=` + item.id,
  });
};

const onToMvDetail = (item: any) => {
  uni.navigateTo({
    url: `/pages/sub/mv/detail?id=` + item.videoId,
  });
};

// 排序回调
const change = (value: any) => {
  data.value = value;
  // 这里可以根据选择的值进行相应的处理
  if (pageRef.value) {
    pageRef.value?.onRefresh?.({ orderBy: value });
  }
};

const pageChange = (list: Music.List.Data['list']) => {
  if(tabIndex.value === 0) {
    data.list = list;
  }
};
const goodSPageChange = (list: User.Order.ProductList[]) => {
  if(tabIndex.value === 2) {
    data.goodsList = list;
  }
};
const mvPageChange = (list: any[]) => {
  if(tabIndex.value === 1) {
    data.mvList = list;
  }
};

const onChangeSubTab = (val:number) => {
  subTab.value = val
  if (goodsPageRef.value) {
    goodsPageRef.value?.onRefresh?.({ type: (val + 1 )});
  }
}

const searchKeyword = () => {
  if (pageRef.value) {
    pageRef.value?.onRefresh?.({ orderBy: data.value, keyword: data.keyword ? data.keyword : '' });
  }
}

const mvSearchKeyword = () => {
  if (mvPageRef.value) {
    mvPageRef.value?.onRefresh?.({  musicName: data.mvKeyword ? data.mvKeyword : '' });
  }
}

// 跳转至商品详情
const onToShopDetail = (item:any) => {
  uni.navigateTo({
    url: '/pages/sub/my/shopDetail?spuId=' + (item.spuId || '') + '&skuId=' + (item.skuId || ''),
  });
}

/**
 * 接口相关
 */
onHide(() => {
  // 页面隐藏时，清理所有组件引用
  if (pageRef.value) pageRef.value = null;
  if (mvPageRef.value) mvPageRef.value = null;
  if (goodsPageRef.value) goodsPageRef.value = null;
});
</script>

<style lang="scss" scoped>
.square-header {
  margin-top: -116rpx;
  .square-tabs {
    display: flex;
    align-items: center;
    padding: 0 32rpx;
    // margin-bottom: 32rpx;
  }
  .tab {
    font-size: 36rpx;
    color: #fff;
    font-weight: 600;
    margin-right: 48rpx;
    opacity: 0.7;
    position: relative;
    padding-bottom: 8rpx;
  }
  .tab.active {
    opacity: 1;
  }
  .tab.active::after {
    content: '';
    display: block;
    width: 37rpx;
    height: 13rpx;
    background-image: url('https://cdn.xmxiaomai.com/isong_static/common/Stroke%201.png');
    background-size: contain;
    background-repeat: no-repeat;
    position: absolute;
    left: 50%;
    bottom: -10rpx;
    transform: translateX(-50%);
  }
}

.square-container {
  min-height: 100vh;
  padding-bottom: 120rpx;
  border-radius: 30rpx 30rpx 0 0;
  overflow: hidden;
  margin-top: 40rpx;
  position: relative;
  z-index: 999;
  background: linear-gradient(180deg, #dff2ee 0%, #f3f6f5 100%);
}
.sort-bar {
  margin: 41rpx 42rpx 60rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.shop-sort-bar {
  margin-bottom: 20rpx;
}
.sort-btn {
  background: #f5f8f7;
  color: #222;
  font-size: 28rpx;
  border-radius: 24rpx;
  border: 2rpx solid #e0e0e0;
  padding: 8rpx 32rpx;
  display: flex;
  align-items: center;
}
.arrow {
  font-size: 24rpx;
  margin-left: 8rpx;
}
.music-list {
  margin: 0 0 0 0;
  margin-top: 0;
}
.music-card {
  display: flex;
  align-items: center;
  margin: 24rpx 43rpx 0 87rpx;
  padding: 25rpx 67rpx 26rpx 155rpx;
  position: relative;
  background: linear-gradient(90deg, #d9f2ec 0%, #ffffff 100%);
  box-shadow: 0rpx 8rpx 11rpx 6rpx rgba(43, 42, 42, 0.09), inset 0rpx 0rpx 8rpx 4rpx #ffffff;
  border-radius: 100rpx;
  border: 2rpx solid #deb893;
}
.music-img {
  width: 172rpx;
  height: 172rpx;
  border-radius: 50%;
  background: #eee;
  margin-right: 24rpx;
  border: 2rpx solid #ffd699;
  flex-shrink: 0;
  position: absolute;
  left: -44rpx;
}
.music-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.music-title {
  font-size: 32rpx;
  color: #222;
  font-weight: 600;
  margin-bottom: 8rpx;
  display: flex;
  justify-content: space-between;
  .music-title-name {
    max-width: 275rpx;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .music-title-score {
    font-weight: 600;
    font-size: 28rpx;
    color: #01604A;
  }
  .music-title-fen {
    font-size: 20rpx;
    color: #01604A;
  }
}
.music-author {
  font-size: 26rpx;
  color: #888;
  margin-bottom: 12rpx;
  max-width: 275rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.music-meta {
  display: flex;
  align-items: center;
}
.meta-item {
  display: flex;
  align-items: center;
  font-size: 26rpx;
  color: #1fa37a;
  margin-right: 32rpx;
}
.music-arrow {
  margin-left: 12rpx;
  display: flex;
  align-items: center;
}
.mall-subtabs {
  display: flex;
  align-items: center;
  background: #eaf8f4;
  border-bottom: 2rpx solid #e0e0e0;
  margin: 0 0 0 0;
  padding: 0 0 0 32rpx;
  justify-content: space-around;
}
.subtab {
  font-size: 32rpx;
  color: #222;
  font-weight: 500;
  margin-right: 48rpx;
  opacity: 0.7;
  padding: 32rpx 0 18rpx 0;
  position: relative;
}
.subtab.active {
  color: #1fa37a;
  opacity: 1;
}
.subtab.active::after {
  content: '';
  display: block;
  width: 48rpx;
  height: 6rpx;
  background: #1fa37a;
  border-radius: 3rpx;
  position: absolute;
  left: 50%;
  bottom: 0;
  transform: translateX(-50%);
}
.sort-btn {
  background: #f5f8f7;
  color: #222;
  font-size: 28rpx;
  border-radius: 24rpx;
  border: 2rpx solid #e0e0e0;
  padding: 8rpx 32rpx;
  display: flex;
  align-items: center;
}
.arrow {
  font-size: 24rpx;
  margin-left: 8rpx;
}
.goods-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  margin: 140rpx 24rpx 0;
}
.goods-card {
  width: 48%;
  background: #eaf8f4;
  border-radius: 20rpx;
  margin-bottom: 140rpx;
  box-shadow: 0 4rpx 16rpx 0 #e0e0e0;
  border: 2rpx solid #ffd699;
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-bottom: 24rpx;
  height: 324rpx;
}
.goods-img {
  width: 200rpx;
  height: 200rpx;
  border-radius: 50%;
  background: #eee;
  margin-top: -100rpx;
  border: 2rpx solid #ffd699;
  flex-shrink: 0;
}
.goods-info {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  margin: 38rpx 26rpx 6rpx;
}
.goods-title {
  font-size: 30rpx;
  color: #222;
  font-weight: 600;
  margin-bottom: 6rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 275rpx;
}
.goods-author {
  font-size: 24rpx;
  color: #888;
  margin-bottom: 22rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 275rpx;
}
.goods-meta {
  display: flex;
  align-items: center;
}
.meta-item {
  display: flex;
  align-items: center;
  font-size: 24rpx;
  color: #545353;
  font-weight: 400;
  margin-right: 24rpx;
  .meta-item-icon {
    width: 24rpx;
    height: 24rpx;
    margin-right: 4rpx;
  }
}
.goods-price-bar {
  width: 100%;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-top: 8rpx;
}
.goods-price {
  background-image: url('https://cdn.xmxiaomai.com/isong_static/square/Rectangle.png');
  background-size: 100% 100%;
  background-repeat: no-repeat;
  color: #523620;
  font-size: 36rpx;
  font-weight: 700;
  height: 62rpx;
  text-align: center;
  line-height: 75rpx;
  padding: 5rpx 30rpx;
  .goods-price-unit {
    font-size: 20rpx;
  }
}
.keyword-search {
  border-radius: 26rpx;
  border: 1rpx solid #01604a;
  padding: 4rpx 20rpx;
  font-size: 28rpx;
  width: 200px;
}

.mv-list {
  padding: 0 30rpx 30rpx;
}

.mv-card {
  width: 50%;
  padding: 20rpx 20rpx 0;
  box-sizing: border-box;
  position: relative;
  display: inline-block;
  vertical-align: top;

  image {
    width: 100%;
    height: 480rpx;
    border-radius: 10rpx;
  }

  .list-item-title {
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
    word-wrap: break-word;
    word-break: break-word;
    line-height: 1.4em;
    max-height: 2.8em;
    text-align: center;
    margin-top: 10rpx;
    font-size: 28rpx;
    min-height: 2em;
  }
}

.search-icon {
  position: absolute;
  right: 20rpx;
  top: 6rpx;
}
</style>
